import { RollupPlugin, RollifyConfigure } from '../typing'
import { merge } from 'node-aux'
import { aliasPlugin } from './alias'
import replace from '@rollup/plugin-replace'
import { modulePlugin } from './module'
import { terserPlugin } from './terser'
import { stylePlugin } from './style'
import { babelPlugin } from './babel'
import { jsonPlugin } from './json'
import { typescriptPlugin } from './typescript'
import lazyStyle from 'rollup-plugin-lazy-style'
export const pluginsConfigure = function <T extends RollifyConfigure>(userConfig: T) {
    const { build, alias, define, scssModule, declaration } = userConfig
    const plugins: (RollupPlugin | undefined)[] = []
    return {
        name: 'plugins',
        configure: (config) => {
            if (alias) {
                plugins.push(aliasPlugin(alias))
            }
            if (define) {
                plugins.push(replace(define))
            }
            if (declaration) {
                plugins.push(
                    typescriptPlugin(declaration?.declarationDir, declaration?.tsconfigPath)
                )
            }
            if (build?.babelType) {
                plugins.push(...modulePlugin(build?.babelType))
            }
            if (build?.isMinify) {
                merge(config, {
                    treeshake: {
                        moduleSideEffects: 'no-external',
                        propertyReadSideEffects: false,
                        tryCatchDeoptimization: false
                    }
                })
                plugins.push(terserPlugin())
            }
            if (build?.babelType) {
                plugins.push(
                    babelPlugin({
                        ...build?.babel,
                        type: build?.babelType,
                        targets: build?.target,
                        jsxImportSource: build?.jsxImportSource
                    })
                )
            }
            if (scssModule) {
                plugins.push(stylePlugin(scssModule))
            }
            plugins.push(jsonPlugin())
            if (build?.style) {
                plugins.push(
                    lazyStyle({
                        entry: './src/components/*/index.scss',
                        ...build.style
                    })
                )
            }

            return plugins.filter(Boolean)
        }
    }
}
